# GPL3 or any later version

import os
import json
import time

import urllib.request
import urllib.parse

import gi
import threading
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GLib

from modules import wallet
from modules import ui

def search_searx(search):

    # This function searches in searx for images

    search = urllib.parse.quote_plus(search)
    url = "https://searx.thegpm.org/?q="+search+"&categories=images&format=json"

    req = urllib.request.Request(url, data=None)

    f = urllib.request.urlopen(req)
    data = json.loads(f.read().decode('utf-8'))

    ret = []
    
    for i in data.get("results",[]):
        if i.get("thumbnail_src"):
            ret.append(i.get("thumbnail_src"))

    return ret

def select_image(win, search):

    # Selector window

    # This will insures that we are not getting by mistake
    # the image from the previous search into here.
    try:
        del win.return_search
    except:
        pass
    
    folder = wallet.save_folder()+"images/"
    try:
        os.makedirs(folder)
    except:
        pass

    
    dialogWindow = Gtk.Dialog("Select Image",
            buttons=(),
        )
    dialogWindow.set_size_request(400, 400)

    box = dialogWindow.get_content_area()
    scrl = Gtk.ScrolledWindow()
    scrl.set_vexpand(0)
    box.pack_start(scrl, 1,1,1)

    pack = Gtk.VBox()
    scrl.add(pack)
    
    def draw(links):

        flowbox = Gtk.FlowBox()
        flowbox.set_valign(Gtk.Align.START)
        flowbox.set_max_children_per_line(30)
        flowbox.set_selection_mode(Gtk.SelectionMode.NONE)

        
        
        for i in links:

            def on_button(w, i, save_as):
                dialogWindow.destroy()
                win.return_search = save_as

            save_as = ui.image_save_name(i,folder)
            
            button = Gtk.Button()
            button.set_relief(Gtk.ReliefStyle.NONE)
            button.connect("clicked", on_button, i, save_as)
            
            image = ui.load(win, ui.net_image_calculation, ui.net_image_render, i, 100 , save_as, False)
            button.add(image)
            flowbox.add(button)
            
        flowbox.show_all()
        return flowbox

    widget = ui.load(win, search_searx, draw, search)
    pack.pack_start(widget, 1,1,1)
    
    box.show_all()
    response = dialogWindow.run()
    dialogWindow.destroy()
    
def clear():

    # This function runs in the end of the runtime to clean images
    # that are not needed.

    imgs = [] # List of images that we should not touch

    # Checking every listed image in items.
    folder = wallet.save_folder()+"items/"
    for i in list(os.walk(folder))[0][2]:

        try:
            with open(folder+i) as json_file: 
                idata = json.load(json_file)
            im = idata.get("image", "")
            if im:
                imgs.append(im)
        except:
            pass

    # Checking evert listed image in merchants.
    folder = wallet.save_folder()+"merchants/"
    for i in list(os.walk(folder))[0][2]:

        try:
            with open(folder+i) as json_file: 
                idata = json.load(json_file)
            im = idata.get("image", "")
            if im:
                imgs.append(im)
        except:
            pas

    # If not listed deleting.
    folder = wallet.save_folder()+"images/"
    for i in list(os.walk(folder))[0][2]:
        img = folder+i
        if not img in imgs:
            try:
                os.remove(img)
            except:
                pass
